/* 
 * This program illustrates the use of the timer primitives 
 * (i.e., cl_set_timer). There are three timer callbacks
 * that are called every 500ms, 2sec, and 5sec, respectively 
 */

#include <stdio.h>
#include <errno.h>
#include "i3_client_api.h"

/* callbacks */
void timer_cbk_500ms(void *data)
{
  struct timeval tv;

  printf("timeout 500 msec\n");
  tv.tv_sec  = 0;
  tv.tv_usec = 500000;
  cl_set_timer(&tv, timer_cbk_500ms, NULL);
}

void timer_cbk_5s(void *data)
{
  struct timeval tv;

  printf("timeout 5 sec\n");
  tv.tv_sec  = 5;
  tv.tv_usec = 0;
  cl_set_timer(&tv, timer_cbk_5s, NULL);
}

void timer_cbk_2s(void *data)
{
  struct timeval tv;

  printf("timeout 2 sec\n");
  tv.tv_sec  = 2;
  tv.tv_usec = 0;
  cl_set_timer(&tv, timer_cbk_2s, NULL);
}



int i3_main_loop(char *cfg_file)
{
  fd_set rset;
  struct timeval tv;
  int rc;

  FD_ZERO(&rset);

  /* initialize context */
  cl_init(cfg_file);

  /* associate callbacks with the inserted trigger */
  tv.tv_sec  = 0;
  tv.tv_usec = 500000;
  cl_set_timer(&tv, timer_cbk_500ms, NULL);
  tv.tv_sec  = 2;
  tv.tv_usec = 0;
  cl_set_timer(&tv, timer_cbk_2s, NULL);
  tv.tv_sec  = 5;
  cl_set_timer(&tv, timer_cbk_5s, NULL);

  for (;;) {
    FD_SET(0, &rset); /* just here, to be modified if application
		       * listens on other fds
		       */
    if ((rc = cl_select(0, &rset, NULL, NULL, NULL)) < 0) {
      if (errno == EINTR)
	continue;
      else
	err_sys("select_error\n");
    }

  }
  
  /* destroy context */
  cl_exit();
}


int main(int argc, char **argv)
{
  if (argc != 2) {
    printf("%s <cfg_file.xml>\n", argv[0]);
    exit(-1);
  }
  
  i3_main_loop(argv[1]);
  return -1;
}

